package com.lagou.registry;

import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * 注册中心服务注册
 * @author 陶肖寅
 * @version V1.0
 * @Package com.lagou.registry
 * @email fromlx@126.com
 * @date 2020-04-07 12:55
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
public class ServiceRegistry {
    /**
     * 注册地址
     */
    private String registryAddress;
    private static String ZK_DATA_PATH="/lg-netty/ip";
    public ServiceRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    //注册到zk中，其中data为服务端的 ip:port
    public void register(String data) {
        if (data != null) {
            ZkClient client = connectServer();
            if (client != null) {
                createNode(client, data);
            }
        }
    }

    /**
     * 连接zookeeper
     * @return
     */
    private ZkClient connectServer() {
        ZkClient client = null;
        try {
            client = new ZkClient(registryAddress ,5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 创建数据结点
     * @param client
     * @param data ip:port
     */
    private void createNode(ZkClient client, String data) {
        try {
            byte[] bytes = data.getBytes();
            String path = client.createEphemeralSequential(ZK_DATA_PATH,data);
            System.out.println("create zookeeper node path:"+path+" data:"+data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
